import * as path from "path";
import * as fs from "fs";

// const outExt = ".js";

export class ImportPathRewrite {
    constructor(private filePath: string, node: babel.types.File, private outExt: string) {
        this.traverse(node);
    }

    private traverse(node: babel.types.Node) {
        switch (node.type) {
            case "Program":
                node.body.forEach(c => this.traverse(c));
                break;
            case "File":
                this.traverse(node.program);
                break;
            case "ImportDeclaration":
                if (node.source.type === "StringLiteral" && node.source.value.startsWith(".")) {
                    let ext = this.extname(node.source.value);
                    if (ext != this.outExt) {
                        let dir = path.dirname(this.filePath);
                        let fullPath = path.join(dir, node.source.value);
                        console.log(`ImportDeclaration: ${fullPath} -> ${ext}`)
                        if (fs.existsSync(fullPath) && fs.statSync(fullPath).isDirectory()) {
                            node.source.value = node.source.value + "/index";
                        }
                        node.source.value += this.outExt;
                    }
                }
                break;

        }
    }

    private extname(file: string) {
        // let ext = /\.[a-zA-Z]+/.exec(file)?.[0] || '';
        let ext = path.extname(file);
        return ext;
    }


}